
clc;
clear all;
close all;


load ParticipationWithSpillover_addEstiProb; % from STATA
[row, col] = size(ParticipationWithSpillover_addEstiProb);

Newmatrix = ParticipationWithSpillover_addEstiProb;
col_year = 1;
col_facilityID = 48;
col_modifiedpart = 51;
col_estiprob = 69;   


Newmatrix(:, (col+1)) = Newmatrix(:, col_estiprob);



facilityIDs = unique(Newmatrix(:,col_facilityID));
for i = 1: length(facilityIDs)
    facilityID = facilityIDs(i);
    index = find(Newmatrix(:,col_facilityID)==facilityID);
    tempmatrix = Newmatrix(index,:);
    index_one = find(tempmatrix(:, col_modifiedpart) == 1);
    if (~isempty(index_one))
        estiprob = Newmatrix(index(index_one), col_estiprob);
    end
    index_99999 = find(tempmatrix(:, col_modifiedpart) == 99999);
    if (~isempty(index_99999))
        Newmatrix(index(index_99999), (col+1)) = estiprob;
    end
end



% 1996~2001 use the same as in 1995
Newmatrix(:, (col+2)) = Newmatrix(:, (col+1));
facilityIDs = unique(Newmatrix(:, col_facilityID));
for i = 1: length(facilityIDs)
    facilityID = facilityIDs(i);
    indexfacility = find(Newmatrix(:, col_facilityID) == facilityID);
    indexyearBefore1995 = find((Newmatrix(indexfacility, col_year)<=1995)& (Newmatrix(indexfacility, col_year)>= 1991));
    if (~isempty(indexyearBefore1995))
       maxyear = max(Newmatrix(indexfacility(indexyearBefore1995), col_year));
       index = find(Newmatrix(indexfacility, col_year)== maxyear);
       indexyearAfter1995 = find(Newmatrix(indexfacility, col_year)>1995);
       if (~isempty(indexyearAfter1995))
          Newmatrix(indexfacility(indexyearAfter1995), col+2) = Newmatrix(indexfacility(index), col+1);
       end
    end
end



addEstiProbRevised = Newmatrix;

save addEstiProbRevised.mat addEstiProbRevised;
xlswrite('addEstiProbRevised',addEstiProbRevised);     

    